/*
Copyright (C) 2014  Johan Degraeve

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/gpl.txt>.

*/

package helpdiabetesj2me;

import java.util.Hashtable;
import javax.microedition.lcdui.Font;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;

/**
 *
 * @author Johan
 */
public class HDProperties {
    
    static private Hashtable mHashtable;
    static RecordStore proprs = null;
    static boolean changed = false;//used to indicate if a change to the hashtable occurred
    
    /**
     * Creates a new instance of HDProperties
     */
    public HDProperties() {
        ;
    }

    //initialises the properties
    //mHashtable is created
    //First an attempt is made to open the RMS "HelpDiabPref"
    //  if this attempt succeeds then the properties are read and stored in the hashtable
    //  if this attempt fails than all properties get a default initial value and are stored in de RMS.
    static private void initialise() {
        byte[] b = null;
        mHashtable = new Hashtable();
        int version;
        int scrwidth;
        boolean smallkeyboard;
        int recordcntr = 1;
        try {
            proprs = RecordStore.openRecordStore("HelpDiabPref",false);
            //first compare to the required version
            b = proprs.getRecord(recordcntr++);
            version = Integer.parseInt(new String(b));
            b = proprs.getRecord(recordcntr++);
            mHashtable.put("Ins_1",Float.parse(new String(b),10));
            b = proprs.getRecord(recordcntr++);
            mHashtable.put("Ins_2",Float.parse(new String(b),10));
            b = proprs.getRecord(recordcntr++);
            mHashtable.put("Ins_3",Float.parse(new String(b),10));
            b = proprs.getRecord(recordcntr++);
            mHashtable.put("Ins_4",Float.parse(new String(b),10));
            b = proprs.getRecord(recordcntr++);
            mHashtable.put("OntbijtTime",new Long(Long.parseLong(new String(b))));
            b = proprs.getRecord(recordcntr++);
            mHashtable.put("MiddagmaalTime",new Long(Long.parseLong(new String(b))));
            b = proprs.getRecord(recordcntr++);
            mHashtable.put("VieruurtjeTime",new Long(Long.parseLong(new String(b))));
          
            if (version > 1) {
                b = proprs.getRecord(recordcntr++);
                mHashtable.put("Snelheidsfactor",new Integer(Integer.parseInt(new String(b))));
                if (version > 2) {
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("LetterGrootte",new Integer(Integer.parseInt(new String(b))));
                    //22/11 : as of now I'm assuming the version shall always be > 2, so this piece of code will not be repeated anymore in the next else block'
                    b = proprs.getRecord(recordcntr++);
                    //added 15/01/2009. Kolom indicates whether user wants to see in additem screen online calculation of eiwit, kcal, vet or koolh
                    mHashtable.put("Kolom",new Integer(Integer.parseInt(new String(b))));
                    //added 11/02/2009 for touch screen devices
                    //following properties indicate if a partical canvas uses small or large keyboard
                    //only effectively used in additem and getitemfromuser
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("AddItemsmallkeyboard",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("DeepSearchsmallkeyboard",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("GetItemFromUsersmallkeyboard",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("InitialScreensmallkeyboard",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("ReadItemListsmallkeyboard",new Boolean(new String(b).equals("true")));
                    //following properties indicate if a partical canvas uses keyboard
                    //only effectively used in additem and getitemfromuser
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("AddItemkeyboardshown",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("DeepSearchkeyboardshown",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("GetItemFromUserkeyboardshown",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("InitialScreenkeyboardshown",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("ReadItemListkeyboardshown",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("touchscreendevice",new Boolean(new String(b).equals("true")));
                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("veryslowdevice",new Boolean(new String(b).equals("true")));

                    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("neverdelete",new Boolean(new String(b).equals("true")));
		    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("askbeforedelete",new Boolean(new String(b).equals("true")));
		    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("questionalreadyasked",new Boolean(new String(b).equals("true")));
		    b = proprs.getRecord(recordcntr++);
                    mHashtable.put("Carbs_Per_Portion",Float.parse(new String(b),10));

                } else {
                    mHashtable.put("LetterGrootte",new Integer(Font.SIZE_MEDIUM));
                    close();
                }
            } else {
                mHashtable.put("Snelheidsfactor",new Integer(-1));
                mHashtable.put("LetterGrootte",new Integer(Font.SIZE_MEDIUM));

                close();
            }
        } catch (RecordStoreNotFoundException e1)  {
            //recordstore not existing, so we'll fill the hashtable up with default values'
            
            // Amounts of grams of kh per unit of insuline, morning
            mHashtable.put("Ins_1",Float.ZERO);
            // Amounts of grams of kh per unit of insuline, noon
            mHashtable.put("Ins_2",Float.ZERO);
            // Amounts of grams of kh per unit of insuline, evening
            mHashtable.put("Ins_3",Float.ZERO);
            // Amounts of grams of kh per unit of insuline, vieruurtje
            mHashtable.put("Ins_4",Float.ZERO);
            //	time when swapping from morning to noon, 
            mHashtable.put("OntbijtTime",new Long(32400000));
            //	time when swapping from noon to evening, 
            mHashtable.put("MiddagmaalTime",new Long(50400000));
            //	time when swapping from noon to evening,
            mHashtable.put("VieruurtjeTime",new Long(61200000));
            //snelheidsfactor
            mHashtable.put("Snelheidsfactor",new Integer(-1));
            //lettergrootte
            mHashtable.put("LetterGrootte",new Integer(Font.SIZE_MEDIUM));
            //what does the user want to see online calculated in additem
            // 0 = kcal
            // 1 = eiwit
            // 2 = koolh
            // 3 = vet
            mHashtable.put("Kolom",new Integer(2));
            //keyboardsize, per class derived from MyCanvas
            smallkeyboard = true;
            mHashtable.put("AddItemsmallkeyboard",new Boolean(smallkeyboard));
            mHashtable.put("DeepSearchsmallkeyboard",new Boolean(smallkeyboard));
            mHashtable.put("GetItemFromUsersmallkeyboard",new Boolean(smallkeyboard));
            mHashtable.put("InitialScreensmallkeyboard",new Boolean(smallkeyboard));
            mHashtable.put("ReadItemListsmallkeyboard",new Boolean(smallkeyboard));
            //keyboardshown or not
            mHashtable.put("AddItemkeyboardshown",new Boolean(false));
            mHashtable.put("DeepSearchkeyboardshown",new Boolean(false));
            mHashtable.put("GetItemFromUserkeyboardshown",new Boolean(false));
            mHashtable.put("InitialScreenkeyboardshown",new Boolean(false));
            mHashtable.put("ReadItemListkeyboardshown",new Boolean(false));
            //touchscreendevice - only one time, although it's called per canvas,
            mHashtable.put("touchscreendevice",new Boolean(false));
            //veryslowdevice
            mHashtable.put("veryslowdevice",new Boolean(false));
            //added 12/06, for deleting present list
            mHashtable.put("neverdelete",new Boolean(false));
            mHashtable.put("askbeforedelete",new Boolean(true));
            mHashtable.put("questionalreadyasked",new Boolean(false));
            mHashtable.put("Carbs_Per_Portion",new Float(150,-1));


            changed  = true;
            close();
            
        } catch (Exception e) {//any unforeseen exception will result in deleting the property recordstore
            try {proprs.closeRecordStore();} catch (Exception ex) {;}
            try {RecordStore.deleteRecordStore("HelpDiabPref");} catch (Exception ex) {;}
            proprs = null;
            (new ReportException()).Report("exception in Properties.load",e,true);
        } finally {
            if (proprs != null) {
                try {proprs.closeRecordStore();
                } catch (Exception ex) {
                    ;
                } 
            }
        }
    }
    
    //needs to be called before application is closed in order to make sure new key values are stored in recordstore
    static public void close() {
        if (changed) {
            writealltors();
        }
    }
    
    //method to write all contents of the hashtale to the recordstore
    // if the recordstore already exists it will be deleted first
    // when the method returns the recordstore is closed.
    static public void writealltors() {
        byte[] b;
        //first close the rs if it allready exists
        try {proprs.closeRecordStore();} catch (Exception ex) {;}
        try {RecordStore.deleteRecordStore("HelpDiabPref");} catch (Exception ex) {;}
        try {
            proprs = RecordStore.openRecordStore("HelpDiabPref",true);
            b = "3".getBytes();
            proprs.addRecord(b,0,b.length);
            
            b = ((Float)mHashtable.get("Ins_1")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Float)mHashtable.get("Ins_2")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Float)mHashtable.get("Ins_3")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Float)mHashtable.get("Ins_4")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Long)mHashtable.get("OntbijtTime")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Long)mHashtable.get("MiddagmaalTime")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Long)mHashtable.get("VieruurtjeTime")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Integer)mHashtable.get("Snelheidsfactor")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Integer)mHashtable.get("LetterGrootte")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Integer)mHashtable.get("Kolom")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("AddItemsmallkeyboard")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("DeepSearchsmallkeyboard")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("GetItemFromUsersmallkeyboard")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("InitialScreensmallkeyboard")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("ReadItemListsmallkeyboard")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("AddItemkeyboardshown")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("DeepSearchkeyboardshown")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("GetItemFromUserkeyboardshown")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("InitialScreenkeyboardshown")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("ReadItemListkeyboardshown")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("touchscreendevice")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("veryslowdevice")).toString().getBytes();
            proprs.addRecord(b,0,b.length);

            b = ((Boolean)mHashtable.get("neverdelete")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("askbeforedelete")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Boolean)mHashtable.get("questionalreadyasked")).toString().getBytes();
            proprs.addRecord(b,0,b.length);
            b = ((Float)mHashtable.get("Carbs_Per_Portion")).toString().getBytes();
            proprs.addRecord(b,0,b.length);

            proprs.closeRecordStore();
            proprs = null;
            changed = false;
        } catch (RecordStoreException ex) {
            (new ReportException()).Report("Exception in HDProperties.writealltors",ex,true);
        }
        
    }
    
    static public Object get (String key) {
        if (mHashtable == null) {
            initialise();
        }
        return mHashtable.get(key);
    }
    
    static public void put (String key, Object value) {
        if (mHashtable == null) {
            initialise();
        }
        mHashtable.put(key,value);
        changed = true;
    }
    
    //if true then available list should not be deleted, without asking
	  public static boolean neverdelete() {
	  	  return ((Boolean)mHashtable.get("neverdelete")).booleanValue();
	  }	

    //if true then available list should not be deleted, without asking
	  public static boolean askbeforedelete() {
	  	  return ((Boolean)mHashtable.get("askbeforedelete")).booleanValue();
	  }	

          //if true then available list should not be deleted, without asking
	  public static boolean questionalreadyasked() {
	  	  return ((Boolean)mHashtable.get("questionalreadyasked")).booleanValue();
	  }

      public static void setquestionalreadyasked(boolean value) {
            HDProperties.put("questionalreadyasked",new Boolean(value));
      }

      public static void setneverdelete(boolean value) {
            HDProperties.put("neverdelete",new Boolean(value));
      }
      public static void setaskbeforedelete(boolean value) {
            HDProperties.put("askbeforedelete",new Boolean(value));
      }

}
